package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.CheckInConfig;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author zxy
 * @date 2025-05-23
 */
@Service
@Slf4j
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;


    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        // 调用MyBatis Plus的getById方法查询入住信息
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        // 调用Mapper层的方法查询入住列表
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        // 调用MyBatis Plus的save方法新增入住
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        // 调用MyBatis Plus的updateById方法修改入住
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        // 调用MyBatis Plus的removeByIds方法批量删除入住
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        // 调用MyBatis Plus的removeById方法删除入住
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     * @param dto 入住申请数据传输对象
     */
    @Override
    public void apply(CheckInApplyDto dto) {
        // 判断老人是否已入住
        log.info("入住办理：{}", dto);
        CheckInElderDto elderInfo = dto.getCheckInElderDto();
        // 拿ELder中的IDcard进行数据库查询id_card_no
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, elderInfo.getIdCardNo()));
        log.info("数据库中的老人信息: {}", elder);
        if(null != elder){
            if(elder.getStatus() == 1 || elder.getStatus() == 2 || elder.getStatus() == 4){
                throw new ServiceException("老人已入住");
            }
        }
        // 更新床位状态，拿到床位ID，进行更新状态，使用行锁来判断当时是否有人操作
        CheckInConfigDto checkConfiginfo = dto.getCheckInConfigDto();
        Long bedId = checkConfiginfo.getBedId();

        // 根据ID进行更新
        int count =bedMapper.updateBedSatus(bedId);
        log.info("更新床位状态: count={}, id={}", count, bedId);
        if (count == 0){
            throw new ServiceException("床位已被占用");
        }
        // 新增或更新老人
        Elder elder1 = addOrUpdateElder(elderInfo, bedId, elder);

        // 新增签约办理
            addContract(dto,elder1);

        // 新增入住信息
        CheckIn checkIn = addCheckIn(dto, elder1);


        // 新增入住配置

        addCheckInInfon(dto,checkIn);

    }

    /**
     * 获取入住配置信息
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getCheckInfo(Long id) {
        //  查询入住信息
      CheckInDetailVo checkInDetailVo =  new CheckInDetailVo();
      // 查询老人信息
        CheckIn checkIn = getById(id);
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        //转换为VO
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        // 查询家属信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> list = JSONUtil.toList(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(list);
        //  查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        //转换为VO
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        // 查询签约办理信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, checkIn.getElderId()));
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

    private void addCheckInInfon(CheckInApplyDto dto,  CheckIn checkIn) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn addCheckIn(CheckInApplyDto dto,Elder elder1) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckIn checkin = BeanUtil.toBean(checkInConfigDto, CheckIn.class);

        checkin.setElderName(elder1.getName());
        checkin.setElderId(elder1.getId());
        checkin.setIdCardNo(elder1.getIdCardNo());
        checkin.setBedNumber(elder1.getBedNumber());
        checkin.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        save(checkin);

        return checkin;
    }

    private void addContract(CheckInApplyDto dto, Elder elder1) {
        CheckInContractDto check = dto.getCheckInContractDto();
        Contract contractInfo = BeanUtil.toBean(check, Contract.class);
        contractInfo.setElderId(elder1.getId().intValue());
        contractInfo.setElderName(elder1.getName());

        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        LocalDateTime startDate = checkInConfigDto.getStartDate();
        LocalDateTime endDate = checkInConfigDto.getEndDate();
        contractInfo.setStartDate(startDate);
        contractInfo.setEndDate(endDate);
        LocalDateTime now = LocalDateTime.now();
        if(endDate.isBefore(now)){
            // 合同一创建就已过期，没意义
            throw new ServiceException("结束日期要大于当前系统日期");
        }
        // 状态值与当前系统时间对比
        if(startDate.isBefore(now)){
            // 开始时间小于当前时间，状态为已生效
            contractInfo.setStatus(1);
        }else{
            // 开始时间大于当前时间，状态为未生效
            contractInfo.setStatus(0);
        }
        // 设置合同编号
        String contractNumber = CodeGenerator.generateContractNumber();

        contractInfo.setContractNumber(contractNumber);
        contractMapper.insert(contractInfo);
        log.info("新增合同成功,id={}", contractInfo.getId());
    }

    private Elder addOrUpdateElder(CheckInElderDto elderInfo,Long bedId,Elder elder1 ) {
        // 通过toBean方法转换为对象，后续进行插入数据库
        Elder elder = BeanUtil.toBean(elderInfo, Elder.class);
         elder.setStatus(1);
         elder.setBedId(bedId);
         // 通过bedid查询bed_number
        String bedNumber = bedMapper.selectBedById(bedId).getBedNumber();
        elder.setBedNumber(bedNumber);
        // 插入老人数据

        if (elder1 == null){
            elderMapper.insert(elder);
        }else{
            elderMapper.updateById(elder);
        }
        return elder;
    }
}
